
'''
无微宝意外险
'''
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from urllib.parse import urlencode
from common.helper import Helper
class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()

        self.name = "无微宝意外险"


    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA":{
                # 年龄段 18 - 55
                "year":[str(i) for i in range(18,56)],
                # 有无社保 Y 有社保 N 无社保
                "socialSec":["Y","N"],
                # 投保对象
                "payObject":["本人/配偶/子女/父母"],
                #产品计划 planA 基础款 planB 升级款 planC尊享款
                "plan":["planA","planB","planC"],

            }
        }

        for k in plan:

            for v in product( plan[k]["year"],plan[k]["socialSec"],plan[k]["payObject"],plan[k]["plan"]):

                if v[3] == "planA":

                    introduce = {

                        '意外身故、残疾':'10 万',
                        '意外门急诊、意外住院医疗':'1 万',
                        '疾病住院医疗':'1 万'
                    }
                elif v[3] == "planB":


                    introduce = {

                        '意外身故、残疾': '20 万',
                        '意外门急诊、意外住院医疗': '2 万',
                        '疾病住院医': '2 万'
                    }

                else:

                    introduce = {'意外身故、残疾': '30 万','意外门急诊、意外住院医疗': '3 万','疾病住院医疗': '3 万'}


                data = "'" + json.dumps( introduce,ensure_ascii=False ) + "'"

                print( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],data))

                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],data) )

                self.mysql._conn.commit()

                print("%s产品信息写入数据库成功"%self.name)


    #执行爬虫
    def filterInfo(self,dt=None,**data):

        if dt["payObject"] == "子女":

            if dt["plan"] == "planA":

                data["random"] = "3057"
                data["plan"] = dt["plan"]
                data["payObject"] = "子女",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]


                return data


            elif dt["plan"] == "planB":

                data["random"] = "9923"
                data["plan"] = dt["plan"]
                data["payObject"] = "子女",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]

                return data

            else:

                data["random"] = "6857"
                data["plan"] = dt["plan"]
                data["payObject"] = "子女",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]

                return data

        else:

            if dt["plan"] == "planA":

                data["random"] = "3057"
                data["plan"] = dt["plan"]
                data["payObject"] = "本人",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]

                return data


            elif dt["plan"] == "planB":


                data["random"] = "9923"
                data["plan"] = dt["plan"]
                data["payObject"] = "子女",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]

                return data


            else:

                data["random"] = "6857"
                data["plan"] = dt["plan"]
                data["payObject"] = "子女",
                data["socialSec"] = dt["socialSec"],
                data["year"] = dt["year"]

                return data


    def requestJson(self, dt=None):

        result = self.filterInfo( dt )

        data = {

            "random": result["random"],
            "productCode": "WWB_ZYYL",
            "insured_insuredRelatedToApplicantName": result["payObject"][0],
            "insured_insuredRelatedToApplicant_old": "1",
            "insured_genderName": "",
            "insured_genderv": "",
            "insuredSeq": "0",
            "insuredOperateType": "add",
            "checkType": "",
            "insured_productTypeId": "1",
            "productTypeId": "1",
            "plan": result["plan"],
            "isDzfp": "0",
            "productSerialNo": "",
            "channel": "10000",
            "insured_occupationClass": "",
            "insured_occupationalType": "",
            "insu_third_occupationName": "",
            "insured_insuredRelatedToApplicant": "1",
            "socialSecurity": result["socialSec"][0],
            "insured_count": "1",
            "insured_fullName": "",
            "insured_idType": "1",
            "insured_idNumber": "",
            "insured_passcode": "",
            "insured_birthDate": "",
            "insured_genderT": "1",
            "isPrint": "N",
            "enterAge": result["year"]
        }


        print( data )

        try:
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                              data=urlencode(data).replace('+', ''))

            print( r.text )

            if r.status_code == 200 and r.json()["flag"]:

                price = Helper.decimalParse( r.json()["grossPremium"])

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price

                }

                self.mysql.updatePrice( data )


            else:

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }

                self.mysql.updateTask( data )

        except Exception as e:

            print( e )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)





